const fse = require('fs-extra')
const path = require('path')
const fs = require("fs");

const chunkPath = `./文字文稿1.pdf-chunks`
const params = {
  fileName: '周杰伦-《印第安老斑鸠》mp3在线音乐歌曲免费下载.mp3',
  size: 1 * 1024 * 1024
}
mergeChunks(`./${params.fileName}-chunks`, params.fileName, params.size)

function mergeChunks(chunkDir, fileName, size) {
  const chunkDirPath = path.resolve(__dirname, `./${chunkDir}`)
  fse.readdir(chunkDirPath).then(files => {
    const paths = files.sort((a, b) => {
      const aIndex = a.replace(`${fileName}-`, '')
      const bIndex = b.replace(`${fileName}-`, '')
      return aIndex - bIndex
    })

    const writeList = paths.map((filePath, index) => {
      const chunkPath = path.resolve(chunkDirPath, filePath)
      const writeStream = fs.createWriteStream(path.resolve(__dirname, './file/'+fileName), {
        start: index * size
      })
      return chunkReadStream(chunkPath, writeStream)
    })

    Promise.all(writeList).then(() => {
      fs.rmdirSync(chunkDirPath)
    })
  });
}

function chunkReadStream(chunkPath, writeStream) {
  return new Promise((resolve) => {
    const readStream = fs.createReadStream(chunkPath)
    readStream.on('end', () => {
      fs.rmSync(chunkPath)
      resolve()
    })
    readStream.pipe(writeStream)
  })
}